<template>
    <div class="e-form">
        <BillTop title="供方预付款结算编辑" @cancel="handleClose"></BillTop>
        <div class="tabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                :rules="rules"
                                ref="ruleForm"
                                label-width="240px"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="结算编号"
                                            prop="billNo"
                                        >
                                            {{ formData.billNo }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="单据机构"
                                            prop="orgName"
                                        >
                                            {{ formData.orgName }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="合同类型"
                                            prop="contractTypeName"
                                        >
                                            {{ formData.contractTypeName }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="合同名称"
                                            prop='contractName'
                                        >
                                            {{ formData.contractName }}&nbsp;
                                            <span
                                                class="a"
                                                @click="onViewContract"
                                                v-if="formData.contractBillId"
                                                >查看</span
                                            >
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="结算单位"
                                            prop="settlementUnitName"
                                        >
                                            <div
                                                style="
                                                    display: flex;
                                                    width: 100%;
                                                "
                                            >
                                                <el-input
                                                    style="
                                                        flex: 1;
                                                        margin: 0 5px 0 0;
                                                    "
                                                    placeholder="请选择合同名称"
                                                    v-model="
                                                        formData.settlementUnitName
                                                    "
                                                    readonly
                                                    v-if="!isRedSingle"
                                                >
                                                    <i
                                                        slot="suffix"
                                                        class="
                                                            el-icon-document-copy
                                                        "
                                                        @click="onSelectHetong"
                                                    ></i>
                                                </el-input>
                                                <span v-else>{{
                                                    formData.settlementUnitName
                                                }}</span>
                                            </div>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="结算日期"
                                            prop="settlementDate"
                                        >
                                            <el-date-picker
                                                v-model="
                                                    formData.settlementDate
                                                "
                                                type="date"
                                                placeholder="请选择结算日期"
                                                value-format="yyyy-MM-dd"
                                                v-if="!isRedSingle"
                                            ></el-date-picker>
                                            <span v-else>{{
                                                formData.settlementDate
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="预付款金额(元)"
                                            prop="amount"
                                        >
                                            <el-input
                                                type="number"
                                                v-enter-float="{
                                                    set: formData,
                                                    key: 'amount'
                                                }"
                                                v-model="formData.amount"
                                                :max="maxAmount"
                                                v-if="!isRedSingle"
                                            ></el-input>
                                            <span v-else>{{
                                                formData.amount
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="币种"
                                            prop="currencyId"
                                        >
                                            {{ formData.currency }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="累计预付款金额(元)"
                                            prop="cumulativeAmount"
                                        >
                                            {{ formData.cumulativeAmount }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="冲预付款金额(元)"
                                            prop="writeOffAmount"
                                        >
                                            {{ formData.writeOffAmount }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="本位币"
                                            prop="baseCurName"
                                        >
                                            {{ formData.baseCurName }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="传输财务共享"
                                            prop="easId"
                                        >
                                            {{ formData.easId ? '已传' : '未传'}}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="状态" prop="state">
                                            {{ getState(formData.state) }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col
                                        :span="12"
                                        v-if="formData.redBillState !== -1"
                                    >
                                        <el-form-item label="冲红单">
                                            <span :style="redBillStateStyle">{{
                                                redBillStateFun
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item
                                            label="备注"
                                            prop="remarks"
                                        >
                                            <el-input
                                                type="textarea"
                                                :rows="2"
                                                resize="none"
                                                placeholder="请输入内容"
                                                v-model="formData.remarks"
                                                maxlength='500'
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="billId"
                            bucketName="supplierPayment"
                            :isView="isRedSingle"
                        />
                    </div>
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ComExaHistory
                            :billType="Number(billType)"
                            @getAuditHistory="getAuditHistory"
                            :tableData="auditHistoryData"
                            ref="ComExaHistory"
                        />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons
                :auditState="auditState"
                @exas="exas"
                :founderId="formData.founderId"
                :state="formData.state"
            />
            <el-button @click="handleClose" style="margin-left: 10px"
                >取消</el-button
            >
        </div>
    </div>
</template>

<script>
import {
    openAppClient,
    selectDataClient,
    throttle,
    downloadFile,
    showLoading,
    hideLoading
} from '@/utils/common'
import { httpGetFile } from '@/utils/request'
import AttachComp from '@/components/common/attachIndex'
// eslint-disable-next-line no-unused-vars
// reverseWritingAdvancePaymentAmount反写冲预付款金额
import request from '@/api/materialSettlement/supplierPayment'
//审核历史
import ComExaHistory from '@/components/common/exaHistory'
import ComExaButtons from '@/components/common/exaButtons'
import { mapState, mapMutations } from 'vuex'
import '@/utils/jquery.scrollTo.min'

let oldRouter = {} // 上一个页面来源
export default {
    components: {
        AttachComp,
        ComExaHistory,
        ComExaButtons
    },
    data () {
        return {
            tabsName: 'baseInfo',
            billType: '1018',
            flowParams: {
                billId: '',
                billType: '',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            //表单数据
            formData: {},
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            val: '', //冲预付款金额（元）
            auditHistoryData: [],
            auditState: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false,
            rules: {
                billNo: [{ required: true, message: '请自动生成结算编号', trigger: ['blur', 'change'] }],
                orgName: [{ required: true, message: '请带出单据机构', trigger: ['blur', 'change'] }],
                settlementDate: [{ required: true, message: '请选择结算日期', trigger: ['blur', 'change'] }],
                contractTypeName: [{ required: true, message: '请带出合同类型', trigger: ['blur', 'change'] }],
                contractName: [{ required: true, message: '请带出合同名称', trigger: ['blur', 'change'] }],
                settlementUnitName: [{ required: true, message: '请选择结算单位', trigger: ['blur', 'change'] }],
                amount: [{ required: true, message: '请填写预付款金额', trigger: ['blur', 'change'] }],
                cumulativeAmount: [{ required: true, message: '请计算累计预付款金额', trigger: ['blur', 'change'] }],
                baseCurName: [{ required: true, message: '请带出本位币', trigger: ['blur', 'change'] }],
            },
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            winEvent: {},
            maxAmount: 0,
            remainingAmount: 0, //合同剩余预付款金额
            paymentAmount: 0, //累计预付款金额
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            isRedSingle: false
        }
    },
    watch: {
        'formData.redBillState' () {
            if (this.formData.redBillState == 3) {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redBillState == 0 ||
                this.formData.redBillState == 1
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redBillState == 2) {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
    },
    computed: {
        ...mapState('contract', ['ctClassify']),
        ...mapState('equip', ['equipData']),
        billId () {
            return this.$route.query.billid
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 20 - this.lastConHeight
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.formData.redBillState) {
            case 0:
                redState = '冲销中'
                break
            case 1:
                redState = '冲销中'
                break
            case 2:
                redState = '已冲销'
                break
            case 3:
                redState = '红单'
                break
            }
            return redState
        }
    },
    created () {
        this.flowParams.billId = this.$route.query.billid
        this.flowParams.billType = this.billType
    },
    mounted () {
        this.auditState = this.$route.params.auditState
        if (!this.auditState) {
            this.getCurrentUnitInfo()
        }
        this.getById()

        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'attach', 'auditHistory']
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
            console.log($idsTop)
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // //预付款金额事件
        // amountEvent (val) {
        //     const tatol = this.paymentAmount + val * 1
        //     console.log(this.remainingAmount, 'this.remainingAmount')
        //     if (tatol > this.remainingAmount) {
        //         this.clientPop(
        //             'err',
        //             '预付款金额不能大于合同预付款金额:' + this.remainingAmount
        //         )
        //         this.formData.amount = this.remainingAmount
        //     }
        //     //更新累计预付款金额
        //     this.formData.cumulativeAmount =
        //         this.paymentAmount + this.formData.amount * 1
        //     //更新本位币
        //     this.formData.baseCurAmount =
        //         (this.formData.baseCurRate * this.formData.amount * 1).toFixed(
        //             2
        //         ) * 1
        // },
        //获取基本信息
        async getById () {
            const res = await request.getPaymentById({
                id: this.billId
            })
            if (res.redBillState == '3') {
                this.isRedSingle = true
            }
            this.formData = res
            // formData.contractAmount // 合同预付款金额
            this.$watch('formData.amount', val => {
                const tatol = this.formData.previousTotalAmount + val * 1
                // 累计预付款金额不能超合同中的预付款金额
                if (tatol > this.formData.contractAmount) {
                    this.clientPop(
                        'err',
                        '累计预付款金额不能超合同中的预付款金额:' + this.formData.contractAmount
                    )
                    this.formData.amount = +(this.formData.contractAmount - this.formData.previousTotalAmount).toFixed(2)
                }
                //更新累计预付款金额
                this.formData.cumulativeAmount = +(+this.formData.previousTotalAmount + +this.formData.amount).toFixed(2)
                //更新本位币
                this.formData.baseCurAmount =
                (this.formData.baseCurRate * this.formData.amount * 1).toFixed(
                    2
                ) * 1
            })
        },
        //获取截止上期末累计预付款金额
        getPreviousTotalAmount (obj) {
            request
                .getPreviousTotalAmount({
                    contractId: obj.contractBillId
                })
                .then(res => {
                    if (res.code) {
                        this.formData.previousTotalAmount = +(res.data) || 0
                        this.formData.cumulativeAmount = +(+this.formData.previousTotalAmount + +this.formData.amount).toFixed(2) || 0
                    } else {
                        this.formData.previousTotalAmount = +(res) || 0
                        this.formData.cumulativeAmount = +(+this.formData.previousTotalAmount + +this.formData.amount).toFixed(2) || 0
                        this.formData.amount = +(this.formData.contractAmount - this.formData.previousTotalAmount).toFixed(2)
                    }
                })
        },
        getCurrentUnitInfo () {
            request.getCurrentUnitInfo(this.flowParams).then(res => {
                this.auditState = res
            })
        },
        // 审核历史列表查询
        async getAuditHistory () {
            this.auditHistoryData = await request.getAuditHistory(
                this.flowParams
            )
        },
        //保存按钮
        async onSave (str) {
            // 已有billId, 不必重复写
            return new Promise((resovle, reject) => {
                this.$refs['ruleForm'].validate(async valid => {
                    if (valid) {
                        try {
                            showLoading()
                            await request.paymentModify(this.formData)
                            if (str !== 'submit') {
                                this.clientPop('suc', '保存成功')
                            } else {
                                // 点击保存并提交
                                resovle()
                            }
                        } catch (error) {
                            reject(error)
                        }finally{
                            hideLoading()
                        }
                    }
                })
            })
        },
        //提交
        async onSubmit () {
            try {
                showLoading()
                await this.onSave('submit')
                await request.flowCommit(this.flowParams)
                this.clientPop('suc', '提交成功', () => {
                    this.$router.replace('/supplierPayment')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            } finally{
                hideLoading()
            }
        },
        onDel () {
            this.clientPop('info', '确定要删除吗?', () => {
                showLoading()
                request
                    .paymentDel({ id: this.billId })
                    .then(() => {
                        this.clientPop('suc', '删除成功', () => {
                            this.$router.replace('/supplierPayment')
                        })
                    })
                    .catch(() => {
                        this.clientPop('err', '删除失败')
                    })
                    .finally(() => {
                        hideLoading()
                    })
            })
        },
        async onUndo () {
            try {
                await request.flowUndoAudit(this.flowParams)
                this.clientPop('suc', '撤回成功', () => {
                    this.$router.replace('/supplierPayment')
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        onNullify () {
            try {
                openAppClient('/nullifyDialog', '填写作废说明', async () => {
                    const auditParams = JSON.parse(
                        localStorage.vuex
                    ).auditParams
                    await request.flowNullify({
                        billId: this.billId,
                        billType: this.billType,
                        nullifyCreated: '',
                        nullifyCreator: '',
                        nullifyCreatorId: '',
                        nullifyDescription: auditParams.nullifyDescription,
                        nullifyReason: auditParams.nullifyReason
                    })
                    this.clientPop('suc', '作废成功', () => {
                        this.$router.replace('/supplierPayment')
                    })
                })
            } catch (error) {
                alert(error.message || '请求出错')
            }
        },
        //取消按钮
        handleClose () {
            if (oldRouter.path === '/supplierPayment') {
                this.$router.back()
            } else {
                this.$router.replace('/supplierPayment')
            }
        },
        onExportTest () {
            httpGetFile({
                url: '/facilityplan/summary/export'
            }).then(data => {
                downloadFile(data)
            })
        },
        //弹框选择机材合同
        onSelectHetong () {
            selectDataClient({
                SelectServiceToken:
                    '/subcontract/thirdParty/getSupplierSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: '', // 接口参数(name为模拟参数)
                Title: '选择机材合同' // 标题
            })
                .then(val => {
                    // this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果')
                    const item = val[0]
                    this.formData.baseCurId = item.baseCurId
                    this.formData.baseCurName = item.baseCurName
                    this.formData.baseCurRate = item.baseCurRate
                    this.formData.amount = item.advanceCharge //默认等于合同预付款金额
                    this.maxAmount = item.advanceCharge
                    this.remainingAmount = item.advanceCharge
                    this.formData.contractAmount = item.advanceCharge // 合同预付款金额,用于下次进入时,不能大于此金额
                    this.formData.contractBillId = item.contractId
                    this.formData.contractName = item.contractName
                    this.formData.contractBillNo = item.contractNumber
                    this.formData.contractTypeValue = item.contractType
                    const findObj = this.ctClassify.contractType.find(
                        typeItem => typeItem.value === item.contractType
                    )
                    if (findObj) {
                        this.formData.contractTypeName = findObj.label
                    }
                    this.formData.currencyId = item.currencyId
                    this.formData.currency = item.currencyName
                    this.formData.settlementUnitId = item.secondPartyId
                    this.formData.settlementUnitName = item.secondPartyName
                    this.getPreviousTotalAmount(this.formData)
                })
                .catch(err => {
                    alert(err.message)
                })
        },
        exas (str) {
            switch (str) {
            case 'submit':
                this.onSave()
                break
            case 'deleteData':
                this.onDel()
                break
            case 'submitCommit':
                this.onSubmit()
                break
            case 'undoAudit':
                this.onUndo()
                break
            case 'nullify':
                this.onNullify()
            }
        },
        //查看合同
        onViewContract () {
            //1物资采购、2周材租赁、3加工、4设备采购、5设备租赁、6服务采购
            let url = ''
            let title = ''
            switch (this.formData.contractTypeValue) {
            case 1:
                url = 'ctMaterialApplyShow'
                title = '物资采购合同'
                break
            case 2:
                url = 'ctRevolvMaterialApplyShow'
                title = '周材租赁合同'
                break
            case 3:
                url = 'processingContractApplyShow'
                title = '加工合同'
                break
            case 4:
                url = 'ctEquipmentPurchaseApplyShow'
                title = '设备采购合同'
                break
            case 5:
                url = 'ctEquipmentLeaseApplyShow'
                title = '设备租赁合同'
                break
            case 6:
                url = 'serviceProcurementApplyShow'
                title = '服务采购合同'
                break
            }
            openAppClient(
                `/${url}?billid=${this.formData.contractBillId}&isview=true`,
                `查看${title}`
            )
        },
        getState (state) {
            const findObj = this.equipData.state.find(
                item => item.value === Number(state)
            )
            return findObj ? findObj.label : ''
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                const lastCon = document.getElementById('auditHistoryCon')
                if (lastCon) {
                    const lastConHeight = lastCon.offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
